package cn.cmkj.auction.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.LogUtil;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cn.cmkj.auction.R;
import cn.cmkj.auction.adapter.OrderListAdapter;
import cn.cmkj.auction.app.Urls;
import cn.cmkj.auction.data.db.User;
import cn.cmkj.auction.data.http.ShuhuaOrder;
import cn.cmkj.auction.ui.OrderDetailActivity;
import cn.cmkj.auction.utils.HttpCallback;
import cn.cmkj.auction.utils.ItemClickSupport;
import cn.cmkj.auction.widget.swipeRecyclerView.MySwipeRecyclerView;

/**
 * Created by cunguoyao on 2017/9/24.
 */
@ContentView(R.layout.fragment_order_list)
public class MyOrderFragment extends BaseFragment implements MySwipeRecyclerView.OnLoadListener {

    private int type;
    private View view;

    @ViewInject(R.id.swipeRecyclerView)
    private MySwipeRecyclerView swipeRecyclerView;

    private List<ShuhuaOrder> mData;
    private OrderListAdapter orderListAdapter;
    private boolean requesting = false;
    private int page = 1;

    public static MyOrderFragment create(int type) {
        MyOrderFragment f = new MyOrderFragment();
        Bundle args = new Bundle();
        args.putInt("type", type);
        f.setArguments(args);
        return f;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getArguments().getInt("type", 0);
        mData = new ArrayList<>();
        orderListAdapter = new OrderListAdapter(getActivity(), mData);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(view !=  null) {
            return view;
        }
        view = x.view().inject(this, inflater, container);
        swipeRecyclerView.getRecyclerView().setLayoutManager(new GridLayoutManager(getActivity(), 1));
        swipeRecyclerView.setAdapter(orderListAdapter);
        ItemClickSupport.addTo(swipeRecyclerView.getRecyclerView()).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, View itemView, int position) {
                ShuhuaOrder item = mData.get(position);
                Intent intent = new Intent(getActivity(), OrderDetailActivity.class);
                intent.putExtra("order", item);
                startActivity(intent);
            }
        });
        swipeRecyclerView.setOnLoadListener(this);
        swipeRecyclerView.setRefreshing(true);
        return view;
    }

    @Override
    public void onRefresh() {
        if(!requesting) {
            page = 1;
            mData.clear();
            fetchData();
        }
    }

    @Override
    public void onLoadMore() {
        if(!requesting) {
            page = page +1;
            LogUtil.e("--onLoadMore:page=" + page);
            fetchData();
        }
    }

    private void fetchData() {
        requesting = true;
        User user = getAccount();
        if(user == null) {
            showLoginDialog(getActivity());
        }else {
            RequestParams params = new RequestParams(Urls.api);
            params.addParameter("method", Urls.orderList);
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
            if(type != 0) {
                //不传值为全部，1 : 待付款, 2,待发货，3 :待收货, 4 : 已完成
                params.addParameter("status", String.valueOf(type));
            }
            params.addParameter("page_no", page);
            params.addParameter("page_size", Urls.pageSize);
            x.http().request(HttpMethod.POST, params, new HttpCallback(getActivity()) {
                @Override
                public void success(String s) {
                    swipeRecyclerView.complete();
                    requesting = false;
                    if(page == 1) mData.clear();
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(s);
                        JSONObject json = jsonObject.optJSONObject("data");
                        JSONArray jsonArray = json.optJSONArray("orderData");
                        List<ShuhuaOrder> temp = ShuhuaOrder.parseFromJsonArray(jsonArray);
                        mData.addAll(temp);
                        orderListAdapter.notifyDataSetChanged();
                        if(Urls.pageSize > temp.size()) {
                            swipeRecyclerView.setLoadMoreEnable(false);
                        }else {
                            swipeRecyclerView.setLoadMoreEnable(true);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void error(Throwable ex, String msg, boolean isOnCallback) {
                    swipeRecyclerView.complete();
                    requesting = false;
                    if(ex != null)ex.printStackTrace();
                    LogUtil.e("---onError-----" + "onError");
                    Toast.makeText(getActivity(), TextUtils.isEmpty(msg) ? "请求失败" : msg, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void cancel(CancelledException e) {
                    swipeRecyclerView.complete();
                    requesting = false;
                }

                @Override
                public void finished() {
                    requesting = false;
                    swipeRecyclerView.complete();
                }
            });
        }
    }
}
